package com.itlong.cloud.controller.user;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.itlong.cloud.POJO.DTO.BaseDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyH5OrderDTO;
import com.itlong.cloud.POJO.DTO.property.PropertyWeChatDTO;
import com.itlong.cloud.POJO.PO.PropertyUserInfoPO;
import com.itlong.cloud.POJO.PO.WeChatOfficialAuthInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyWeChatVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.annotation.UnParamEncrypt;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.PaySourceEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.paymenthub.IWeChatPayServiceClient;
import com.itlong.cloud.project.property.IPropertyCommunityInfoServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.property.IPropertyWeChatServiceClient;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      物业微信支付相关控制器
 * </desc>
 *
 * @createDate 2019/09/09
 */
@RestController
@RequestMapping("/user/weChatPay")
@RefreshScope
public class PropertyWeChatController extends BaseController {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyWeChatController.class);

//    @Value("${" + PlatformConstants.WECHAT_OFFICIAL_APPID + "}")
//    public String WECHAT_OFFICIAL_APPID;
//
//    @Value("${" + PlatformConstants.WECHAT_OFFICIAL_SECRET + "}")
//    public String WECHAT_OFFICIAL_SECRET;

    @Value("${" + PlatformConstants.THIRD_PARTY_APP_SECRET + "}")
    public String THIRD_PARTY_APP_SECRET;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IPropertyWeChatServiceClient iPropertyWeChatServiceClient;

    @Autowired
    private IPropertyCommunityInfoServiceClient iPropertyCommunityInfoServiceClient;

    @Autowired
    private IWeChatPayServiceClient weChatPayServiceClient;

    /**
     * <desc>
     *      获取预授权码
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/09/09
     */
    @ResponseBody
    @PostMapping(path = "/getPreAuthCode")
    public Object getPreAuthCode(BaseDTO baseDTO){
        try {
            // 发布正式之后，除正式环境外的其它环境禁用此功能
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            baseDTO = HttpProtocolUtil.parseRequestParamToDTO(BaseDTO.class, request);
            String requestURL = request.getRequestURL().toString();
            // 因Nginx接收请求是https端口为443，之后转发到各服务时是http且端口为对应服务端口，所以进行处理
            requestURL = requestURL.replace("http://", "https://");
//            if (!requestURL.contains("https://property.jia-r.com")) {
//                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), "已发布正式环境，其它环境均已禁用！");
//            }

            if (baseDTO == null || StringUtils.isBlank(baseDTO.getLoginUserId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(baseDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            // 校验管理员身份
            PropertyUserInfoPO propertyUserInfoPO = iPropertyCommunityInfoServiceClient.getPropertyUserInfoByUserId(baseDTO.getLoginUserId());
            if (!("3".equals(propertyUserInfoPO.getRoleId()) || "4".equals(propertyUserInfoPO.getRoleId()) || "5".equals(propertyUserInfoPO.getRoleId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_USER_ADMIN_ERR.getErrorCode());
            }

            // 从缓存中拿到component_verify_ticket
            Map<Object, Object> ticketMap = (Map<Object, Object>) redisService.getObject(RedisConstant.WECHAT_COMPONENT_VERIFY_TICKET, Map.class);
            if (ticketMap == null || ticketMap.isEmpty()) {
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), "后台服务未接收到微信推送授权ticket");
            }
            LOG.info("ticketMap："+ticketMap.toString());
            // 获取第三方平台component_access_token
            String componentAccessToken = redisService.get(RedisConstant.WECHAT_COMPONENT_ACCESS_TOKEN);
            if (StringUtils.isBlank(componentAccessToken)) {
                Map<String, Object> getTokenMap = new HashMap<>();
                getTokenMap.put("component_appid", ticketMap.get("AppId"));
                getTokenMap.put("component_appsecret", THIRD_PARTY_APP_SECRET);
                getTokenMap.put("component_verify_ticket", ticketMap.get("ComponentVerifyTicket"));
                LOG.info("获取预授权码时获取componentAccessToken的参数：" + JSON.toJSONString(getTokenMap));
                String tokenResult = HttpProtocolUtil.httpPost("https://api.weixin.qq.com/cgi-bin/component/api_component_token", JSON.toJSONString(getTokenMap));
                Map<String, Object> tokenResultMap = JsonUtil.decode(tokenResult, new TypeReference<Map<String, Object>>() {});
                LOG.info("tokenResultMap:" + tokenResultMap);
                LOG.info("tokenResult"+ tokenResult);
                Object tokenObject = tokenResultMap.get("component_access_token");
                if (tokenObject != null) {
                    componentAccessToken = tokenObject.toString();
                } else {
                    LOG.info("获取预授权码时获取componentAccessToken失败，服务器通讯失败1");
                    return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), "服务器通讯暂时不可用，请稍后再试！");
                }
                redisService.set(RedisConstant.WECHAT_COMPONENT_ACCESS_TOKEN, RedisConstant.WECHAT_COMPONENT_ACCESS_TOKEN_TIME, componentAccessToken);
            }
            // 获取预授权码，多个同时进行授权分别获取有否影响暂时未知，后续考虑预授权码也放至缓存
            Map<String, Object> getPreAuthCodeMap = new HashMap<>();
            getPreAuthCodeMap.put("component_appid", ticketMap.get("AppId"));
            String codeResult = HttpProtocolUtil.httpPost("https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" + componentAccessToken,
                    JSON.toJSONString(getPreAuthCodeMap));
            Map<String, Object> codeResultMap = JsonUtil.decode(codeResult, new TypeReference<Map<String, Object>>() {});
            Object codeObject = codeResultMap.get("pre_auth_code");
            if (codeObject == null) {
                LOG.info("获取预授权码失败，服务器通讯失败2");
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), "服务器通讯暂时不可用，请稍后再试！");
            }
            Map<String, Object> data = new HashMap<>();
            data.put("preAuthCode", codeObject.toString());
            // 改配置文件麻烦，动态生成回调URI
//            requestURL = requestURL.replace("property", "foreign");
            LOG.info("授权入口地址："+requestURL);
            requestURL = requestURL.substring(0, requestURL.indexOf(".c") + 4);
//            requestURL += "/foreign/receive/weChat/receiveAuthCode/" + baseDTO.getLoginUserId();
            requestURL += "/property/user/weChatPay/receiveAuthCode/" + baseDTO.getLoginUserId();
            LOG.info("授权回调地址："+requestURL);
            data.put("redirectUri", requestURL);
            data.put("componentAppId", ticketMap.get("AppId"));
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】获取预授权码失败", e);
        }
    }

    /**
     * <desc>
     *      接收微信回调的授权码和过期时间
     * </desc>
     *
     * @return 字符串success
     * @author wangzhi
     * @createDate 2019/09/09
     */
    @UnAuthAccessRequired
    @RequestMapping("receiveAuthCode/{userId}")
    @UnParamEncrypt
    public void receiveAuthCode(@PathVariable(name = "userId") String userId){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestURL = request.getRequestURL().toString();
        requestURL = requestURL.substring(0, requestURL.indexOf(".c") + 4);
        try {
            LOG.info("微信公众号授权回调进入，userId=" + userId+"requestUrl=" + requestURL);
            // 拿到授权码
            String authCode = request.getParameter("auth_code");
            // 用一个PO对象初步保存一些信息，然后发到service进行处理
            WeChatOfficialAuthInfoPO weChatOfficialAuthInfoPO = new WeChatOfficialAuthInfoPO();
            weChatOfficialAuthInfoPO.setPropertyUserId(userId);
            // 通过授权码调用公众相关API
            // 从缓存中拿到component_verify_ticket
            Map<Object, Object> ticketMap = (Map<Object, Object>) redisService.getObject(RedisConstant.WECHAT_COMPONENT_VERIFY_TICKET, Map.class);
            // 获取第三方平台component_access_token
            String componentAccessToken = redisService.get(RedisConstant.WECHAT_COMPONENT_ACCESS_TOKEN);
            if (StringUtils.isBlank(componentAccessToken)) {
                Map<String, Object> getTokenMap = new HashMap<>();
                getTokenMap.put("component_appid", ticketMap.get("AppId"));
                getTokenMap.put("component_appsecret", THIRD_PARTY_APP_SECRET);
                getTokenMap.put("component_verify_ticket", ticketMap.get("ComponentVerifyTicket"));
                String tokenResult = HttpProtocolUtil.httpPost("https://api.weixin.qq.com/cgi-bin/component/api_component_token", JSON.toJSONString(getTokenMap));
                Map<String, Object> tokenResultMap = JsonUtil.decode(tokenResult, new TypeReference<Map<String, Object>>() {});
                Object tokenObject = tokenResultMap.get("component_access_token");
                if (tokenObject != null) {
                    componentAccessToken = tokenObject.toString();
                } else {
                    // 后续要有一个获取token失败的备用处理方案
                    response.sendRedirect(requestURL);
                }
                redisService.set(RedisConstant.WECHAT_COMPONENT_ACCESS_TOKEN, RedisConstant.WECHAT_COMPONENT_ACCESS_TOKEN_TIME, componentAccessToken);
            }
            // 使用授权码换取公众号或小程序的接口调用凭据和授权信息
            Map<String, Object> getApiAuthMap = new HashMap<>();
            getApiAuthMap.put("component_appid", ticketMap.get("AppId"));
            getApiAuthMap.put("authorization_code", authCode);
            String apiAuthResult = HttpProtocolUtil.httpPost("https://api.weixin.qq.com/cgi-bin/component/api_query_auth?component_access_token=" + componentAccessToken,
                    JSON.toJSONString(getApiAuthMap));
            weChatOfficialAuthInfoPO.setRawInformation("接口调用凭据和授权信息：" + apiAuthResult);
            Map<String, Object> apiAuthResultMap = JsonUtil.decode(apiAuthResult, new TypeReference<Map<String, Object>>() {});
            // 获取授权方appid
            String authorizerAppid = ((Map<String, Object>) apiAuthResultMap.get("authorization_info")).get("authorizer_appid") + "";
            weChatOfficialAuthInfoPO.setAppId(authorizerAppid);
            // 获取授权方的帐号基本信息
            Map<String, Object> getAuthInfoMap = new HashMap<>();
            getAuthInfoMap.put("component_appid", ticketMap.get("AppId"));
            getAuthInfoMap.put("authorizer_appid", authorizerAppid);
            String authInfoResult = HttpProtocolUtil.httpPost("https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?component_access_token=" + componentAccessToken,
                    JSON.toJSONString(getAuthInfoMap));
            weChatOfficialAuthInfoPO.setRawInformation(weChatOfficialAuthInfoPO.getRawInformation() + "&授权方的帐号基本信息：" + authInfoResult);
            Map<String, Object> authInfoResultMap = JsonUtil.decode(authInfoResult, new TypeReference<Map<String, Object>>() {});
            weChatOfficialAuthInfoPO.setPrincipalName(((Map<String, Object>) authInfoResultMap.get("authorizer_info")).get("principal_name") + "");
            weChatOfficialAuthInfoPO.setNickName(((Map<String, Object>) authInfoResultMap.get("authorizer_info")).get("nick_name") + "");
            weChatOfficialAuthInfoPO.setServiceTypeInfo(Integer.parseInt(
                    ((Map<String, Object>) ((Map<String, Object>) authInfoResultMap.get("authorizer_info")).get("service_type_info")).get("id") + ""));
            weChatOfficialAuthInfoPO.setVerifyTypeInfo(Integer.parseInt(
                    ((Map<String, Object>) ((Map<String, Object>) authInfoResultMap.get("authorizer_info")).get("verify_type_info")).get("id") + ""));
            iPropertyWeChatServiceClient.saveWeChatAuthInfoCallBack(weChatOfficialAuthInfoPO);
            response.sendRedirect(requestURL);
        } catch (Exception e) {
            LOG.info("接收授权码发生异常：" + e);
            try {
                response.sendRedirect(requestURL);
            } catch (IOException e1) {
                LOG.info("接收授权码发生异常切重定向异常：" + e1);
            }
        }
    }

    /**
     * <desc>
     *      添加公众号AppSecret
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/11/05
     */
    @AuthAccessRequired
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.PROPERTY_WE_CHAT_SAVE_APP_SECRET)
    @PostMapping(path = "/saveAppSecret")
    public Object saveAppSecret(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            PropertyWeChatDTO propertyWeChatDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWeChatDTO.class, request);
            if (propertyWeChatDTO == null || StringUtils.isBlank(propertyWeChatDTO.getAppSecret()) || StringUtils.isBlank(propertyWeChatDTO.getAppId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyWeChatDTO.getLoginUserId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_LOGINUSERID_TOKEN_EMPTY_ERR.getErrorCode());
            }
            // 校验管理员身份
            PropertyUserInfoPO propertyUserInfoPO = iPropertyCommunityInfoServiceClient.getPropertyUserInfoByUserId(propertyWeChatDTO.getLoginUserId());
            if (!("3".equals(propertyUserInfoPO.getRoleId()) || "4".equals(propertyUserInfoPO.getRoleId()) || "5".equals(propertyUserInfoPO.getRoleId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_USER_ADMIN_ERR.getErrorCode());
            }
            iPropertyWeChatServiceClient.saveAppSecret(propertyWeChatDTO);
            return new MessageVO(propertyWeChatDTO.getAppId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】添加公众号AppSecret失败", e);
        }
    }

    /**
     * <desc>
     *      获取公众号列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/10/21
     */
    @AuthAccessRequired
    @ResponseBody
    @PostMapping(path = "/getAppIdPage")
    public Object getAppIdPage(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            BaseDTO baseDTO = HttpProtocolUtil.parseRequestParamToDTO(BaseDTO.class, request);
            if (baseDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(baseDTO.getLoginUserId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_LOGINUSERID_TOKEN_EMPTY_ERR.getErrorCode());
            }
            Page<PropertyWeChatVO> page = iPropertyWeChatServiceClient.getAppIdPage(baseDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】获取公众号列表失败", e);
        }
    }

    /**
     * <desc>
     *      查看用户授权
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/10/21
     */
    @AuthAccessRequired
    @ResponseBody
    @PostMapping(path = "/getOneAppId")
    public Object getOneAppId(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            PropertyWeChatDTO propertyWeChatDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWeChatDTO.class, request);
            if (propertyWeChatDTO == null || StringUtils.isBlank(propertyWeChatDTO.getInfoId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyWeChatDTO.getLoginUserId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_LOGINUSERID_TOKEN_EMPTY_ERR.getErrorCode());
            }
            PropertyWeChatVO propertyWeChatVO = iPropertyWeChatServiceClient.getOneAppId(propertyWeChatDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), propertyWeChatVO);
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】查看用户授权失败", e);
        }
    }

    /**
     * <desc>
     *      解除微信公众号绑定
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/10/21
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PROPERTY_WE_CHAT_DELETE_APP_ID_BINDING_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "/deleteAppIdBinding")
    public Object deleteAppIdBinding(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            PropertyWeChatDTO propertyWeChatDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWeChatDTO.class, request);
            if (propertyWeChatDTO == null || StringUtils.isBlank(propertyWeChatDTO.getAppId()) || StringUtils.isBlank(propertyWeChatDTO.getLoginUserId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            // 校验管理员身份
            PropertyUserInfoPO propertyUserInfoPO = iPropertyCommunityInfoServiceClient.getPropertyUserInfoByUserId(propertyWeChatDTO.getLoginUserId());
            if (!("3".equals(propertyUserInfoPO.getRoleId()) || "4".equals(propertyUserInfoPO.getRoleId()) || "5".equals(propertyUserInfoPO.getRoleId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_USER_ADMIN_ERR.getErrorCode());
            }
            Integer result = iPropertyWeChatServiceClient.deleteAppIdBinding(propertyWeChatDTO);
            if (result == 0) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_WE_CHAT_AUTH_EXIST_ERR.getErrorCode(), "该公众号不属于您，无权解除绑定");
            }
            return new MessageVO(propertyWeChatDTO.getAppId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】解除微信公众号绑定失败", e);
        }
    }

    /**
     * <desc>
     *      获取用户授权的appId
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/09/09
     */
    @ResponseBody
    @PostMapping(path = "/getAppId")
    public Object getAppId(BaseDTO baseDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            baseDTO = HttpProtocolUtil.parseRequestParamToDTO(BaseDTO.class, request);
            if (baseDTO == null || StringUtils.isBlank(baseDTO.getLoginUserId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(baseDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            List<Map<String, Object>> data = iPropertyWeChatServiceClient.getAppId(baseDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】获取用户授权的appId失败", e);
        }
    }

    /**
     * <desc>
     *      添加appId对应商户号
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/09/10
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PROPERTY_WE_CHAT_SAVE_MCH_ID_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "/saveMchId")
    public Object saveMchId(PropertyWeChatDTO propertyWeChatDTO) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyWeChatDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWeChatDTO.class, request);
            if (propertyWeChatDTO == null || StringUtils.isBlank(propertyWeChatDTO.getLoginUserId())
                    || StringUtils.isBlank(propertyWeChatDTO.getAppId()) || StringUtils.isBlank(propertyWeChatDTO.getMchId()) || StringUtils.isBlank(propertyWeChatDTO.getApiKey())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyWeChatDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            // 校验管理员身份
            PropertyUserInfoPO propertyUserInfoPO = iPropertyCommunityInfoServiceClient.getPropertyUserInfoByUserId(propertyWeChatDTO.getLoginUserId());
            if (!("3".equals(propertyUserInfoPO.getRoleId()) || "4".equals(propertyUserInfoPO.getRoleId()) || "5".equals(propertyUserInfoPO.getRoleId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_USER_ADMIN_ERR.getErrorCode());
            }
            Integer result = iPropertyWeChatServiceClient.saveMchId(propertyWeChatDTO);
            if (result == -1) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_WE_CHAT_AUTH_EXIST_ERR.getErrorCode());
            }
            return new MessageVO(propertyWeChatDTO.getLoginUserId() + "-" + propertyWeChatDTO.getAppId() + "-" + propertyWeChatDTO.getMchId(),
                    BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】添加appId对应商户号失败", e);
        }
    }
//
//    /**
//     * <desc>
//     *      获取单个商户号
//     * </desc>
//     *
//     * @return 标准格式化响应结果
//     * @author wangzhi
//     * @createDate 2019/11/01
//     */
//    @ResponseBody
//    @PostMapping(path = "/getOneMchId")
//    public Object getOneMchId() {
//        try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            PropertyWeChatDTO propertyWeChatDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWeChatDTO.class, request);
//            if (propertyWeChatDTO == null || StringUtils.isBlank(propertyWeChatDTO.getInfoId())) {
//                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
//            }
//            PropertyWeChatVO propertyWeChatVO = iPropertyWeChatServiceClient.getOneAppId(propertyWeChatDTO);
//            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), propertyWeChatVO);
//        } catch (Exception e) {
//            throw new DataAccessException("【物业_微信支付相关】获取单个商户号失败", e);
//        }
//    }

    /**
     * <desc>
     *      修改appId对应商户号
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/10/22
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PROPERTY_WE_CHAT_UPDATE_MCH_ID_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "/updateMchId")
    public Object updateMchId(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            PropertyWeChatDTO propertyWeChatDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWeChatDTO.class, request);
            if (propertyWeChatDTO == null || StringUtils.isBlank(propertyWeChatDTO.getLoginUserId()) || StringUtils.isBlank(propertyWeChatDTO.getInfoId())
                    || StringUtils.isBlank(propertyWeChatDTO.getAppId()) || StringUtils.isBlank(propertyWeChatDTO.getMchId()) || StringUtils.isBlank(propertyWeChatDTO.getApiKey())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyWeChatDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            // 校验管理员身份
            PropertyUserInfoPO propertyUserInfoPO = iPropertyCommunityInfoServiceClient.getPropertyUserInfoByUserId(propertyWeChatDTO.getLoginUserId());
            if (!("3".equals(propertyUserInfoPO.getRoleId()) || "4".equals(propertyUserInfoPO.getRoleId()) || "5".equals(propertyUserInfoPO.getRoleId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_USER_ADMIN_ERR.getErrorCode());
            }
            Integer result = iPropertyWeChatServiceClient.updateMchId(propertyWeChatDTO);
            if (result == 0) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_WE_CHAT_AUTH_EXIST_ERR.getErrorCode(), "该公众号不属于您，无权修改或AppID不可修改");
            }
            return new MessageVO(propertyWeChatDTO.getInfoId() + "-" + propertyWeChatDTO.getLoginUserId() + "-" + propertyWeChatDTO.getAppId() + "-" + propertyWeChatDTO.getMchId(),
                    BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】修改appId对应商户号失败", e);
        }
    }

    /**
     * <desc>
     *      分页查询appId和商户号信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/09/10
     */
    @AuthAccessRequired
    @ResponseBody
    @PostMapping(path = "/getMchIdPage")
    public Object getMchIdPage(PropertyWeChatDTO propertyWeChatDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyWeChatDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWeChatDTO.class, request);
            if (propertyWeChatDTO == null || StringUtils.isBlank(propertyWeChatDTO.getLoginUserId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyWeChatDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            Page<PropertyWeChatVO> propertyWeChatVOPage = iPropertyWeChatServiceClient.getMchIdPage(propertyWeChatDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), propertyWeChatVOPage);
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】分页查询appId和商户号信息失败", e);
        }
    }

    /**
     * <desc>
     *      解除商户号绑定
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/10/22
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.PROPERTY_WE_CHAT_DELETE_MCH_ID_BINDING_LOG_DESC)
    @ResponseBody
    @PostMapping(path = "/deleteMchIdBinding")
    public Object deleteMchIdBinding(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            PropertyWeChatDTO propertyWeChatDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyWeChatDTO.class, request);
            if (propertyWeChatDTO == null || StringUtils.isBlank(propertyWeChatDTO.getLoginUserId()) || StringUtils.isBlank(propertyWeChatDTO.getInfoId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (StringUtils.isBlank(propertyWeChatDTO.getProjectId())) {
                return new MessageVO(PropertyErrorCodeEnum.PUB_PROJECT_ID_EMPTY_ERR.getErrorCode());
            }
            // 校验管理员身份
            PropertyUserInfoPO propertyUserInfoPO = iPropertyCommunityInfoServiceClient.getPropertyUserInfoByUserId(propertyWeChatDTO.getLoginUserId());
            if (!("3".equals(propertyUserInfoPO.getRoleId()) || "4".equals(propertyUserInfoPO.getRoleId()) || "5".equals(propertyUserInfoPO.getRoleId()))) {
                return new MessageVO(PropertyErrorCodeEnum.PROPERTY_USER_ADMIN_ERR.getErrorCode());
            }
            Integer result = iPropertyWeChatServiceClient.deleteMchIdBinding(propertyWeChatDTO);
            if (result == 0) {
                return new MessageVO(PropertyErrorCodeEnum.PROJECT_WE_CHAT_AUTH_EXIST_ERR.getErrorCode(), "该公众号不属于您，无权解除绑定");
            }
            return new MessageVO(propertyWeChatDTO.getInfoId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】解除商户号绑定失败", e);
        }
    }

    /**
     * <desc>
     *      H5支付统一下单
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/09/10
     */
    @UnAuthAccessRequired
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.WECHAT_PAYMENT_ORDER)
    @PostMapping(path = "/order")
    public Object saveOrder(PropertyH5OrderDTO propertyH5OrderDTO){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            propertyH5OrderDTO = HttpProtocolUtil.parseRequestParamToDTO(PropertyH5OrderDTO.class, request);
            if (propertyH5OrderDTO == null || StringUtils.isBlank(propertyH5OrderDTO.getTotal()) || StringUtils.isBlank(propertyH5OrderDTO.getFeeType())
                    || StringUtils.isBlank(propertyH5OrderDTO.getBillsId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //LOG.info("======H5支付统一下单参数：" + propertyH5OrderDTO);
            Map<Object, Object> data = weChatPayServiceClient.saveOrder(propertyH5OrderDTO.getTotal(), propertyH5OrderDTO.getLoginUserId(), propertyH5OrderDTO.getBillsId(),
                    propertyH5OrderDTO.getFeeType(), propertyH5OrderDTO.getOpenId(), PaySourceEnum.H5_SOURCE.getType(), propertyH5OrderDTO.getDeviceUnique(),null,request.getRemoteAddr(),null,null);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【物业_微信支付相关】H5支付统一下单失败", e);
        }
    }

}
